package com.hrhx.springboot.crawler.plugins.net.webdriver;

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.Collections;

/**
 * @author duhongming
 * @version 1.0
 * @description Chrome浏览器创建工厂
 * @date 2019/11/27 10:47
 */
public class ChromeWebDriverFactory implements WebDriverManager {

    public static final ChromeWebDriverFactory me = new ChromeWebDriverFactory();

    public void ChromeWebDriverFactory() {
        //Google浏览器驱动配置
        System.setProperty("webdriver.chrome.driver", "/Users/admin/JavaProject/WebCollector/src/main/resources/driver/chromedriver");
    }

    @Override
    public WebDriver getNewInstance(Boolean useProxy) {
        //是否使用代理
        DesiredCapabilities cap = new DesiredCapabilities();
        if (useProxy) {
            settingProxy(cap);
        }

        settingOptions(cap);

        ChromeDriver driver = new ChromeDriver(cap);

        settingManage(driver);
        return driver;
    }

    /**
     * 设置代理
     *
     * @param cap
     */
    private void settingProxy(DesiredCapabilities cap) {
        Proxy proxy = new Proxy();
        //TODO 代理池
        String proxyIpAndPort = "183.129.244.16:48155";
        proxy.setHttpProxy(proxyIpAndPort).setFtpProxy(proxyIpAndPort).setSslProxy(proxyIpAndPort);
        cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
        cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
        System.setProperty("http.nonProxyHosts", "localhost");
        cap.setCapability(CapabilityType.PROXY, proxy);
    }

    /**
     * 设置启动参数
     */
    private void settingOptions(DesiredCapabilities cap) {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("ignore-certificate-errors");
        // 设置chrome浏览器的参数,使其不弹框提示（chrome正在受自动测试软件的控制）
        options.addArguments("disable-infobars");
        // 开启开发者模式,跳过网站webdriver检测,例如七麦会检测直接跳到404页面
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        cap.setCapability(ChromeOptions.CAPABILITY, options);
    }

    /**
     * 设置浏览器
     */
    public void settingManage(ChromeDriver driver) {
        driver.manage().window().maximize();
//        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//        //切记 此处 WebCollector中selenium-java依赖是3.4 需要排除依赖使用3.5
//        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//        driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
    }
}